package com.jzo2o.customer.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageHelperUtils;
import io.undertow.util.BadRequestException;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    @Resource
    private AddressBookMapper addressBookMapper;

    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {

        List<AddressBook> addressBooks = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getCity, city)
                .list();
        if(CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }

    @Override
    public void add(AddressBookUpsertReqDTO reqDTO) {
        Long userId = UserContext.currentUserId();
        if(reqDTO.getIsDefault() == 1) {
            // 先将该用户的所有地址簿设置为非默认
            lambdaUpdate()
                    .eq(AddressBook::getUserId, userId)
                    .set(AddressBook::getIsDefault, 0)
                    .update();
        }
        AddressBook addressBook = new AddressBook();
        BeanUtils.copyProperties(reqDTO, addressBook);
        addressBook.setUserId(UserContext.currentUser().getId());

        // 处理经纬度字段转换
        if (reqDTO.getLocation() != null) {
            String[] location = reqDTO.getLocation().split(",");
            if (location.length >= 2) {
                try {
                    addressBook.setLon(Double.parseDouble(location[0]));
                    addressBook.setLat(Double.parseDouble(location[1]));
                } catch (NumberFormatException e) {
                    log.error("解析经纬度失败: {}");
                    // 设置默认经纬度或抛出异常
                    addressBook.setLon(0.0);
                    addressBook.setLat(0.0);
                }
            }
        }

        this.save(addressBook);
    }

    @Override
    public PageResult<AddressBookResDTO> pageQueryAddressBook(AddressBookPageQueryReqDTO addressBookPageQueryReqDTO) {
        Long UserId = UserContext.currentUser().getId();
        return PageHelperUtils.selectPage(addressBookPageQueryReqDTO, () -> baseMapper.queryAddressBookList(addressBookPageQueryReqDTO,UserId));
    }

    @Override
    public AddressBookResDTO findById(Long id) {
        AddressBook addressBook = getById(id);
        if(addressBook == null) {
            throw new ForbiddenOperationException("该地址不存在");
        }
        return BeanUtils.copyProperties(addressBook, AddressBookResDTO.class);
    }

    @Override
    public void updateAddressById(Long id, AddressBookUpsertReqDTO reqDTO) {
        if(reqDTO.getIsDefault() == 1) {
            // 先将该用户的所有地址簿设置为非默认
            lambdaUpdate()
                   .eq(AddressBook::getUserId, UserContext.currentUserId())
                   .set(AddressBook::getIsDefault, 0)
                   .update();
        }
        AddressBook addressBook = getById(id);
        if(addressBook == null) {
            throw new ForbiddenOperationException("该地址不存在");
        }
        BeanUtils.copyProperties(reqDTO, addressBook);
        this.updateById(addressBook);
    }

    @Override
    public void deleteById(List<Long> ids) {
       for(Long id : ids) {
           AddressBook addressBook = getById(id);
           if(addressBook == null) {
               throw new ForbiddenOperationException("该地址不存在");
           }
       }
        addressBookMapper.removeByIds(ids);
    }

    @Override
    public void updateDefault(Long id, Long flag) {
        AddressBook addressBook = getById(id);
        if(addressBook == null) {
            throw new ForbiddenOperationException("该地址不存在");
        }
        if(flag == 1) {
            // 先将该用户的所有地址簿设置为非默认
            lambdaUpdate()
                  .eq(AddressBook::getUserId, UserContext.currentUserId())
                  .set(AddressBook::getIsDefault, 0)
                    .update();
        }
        addressBook.setIsDefault(Integer.parseInt(flag.toString()));
        this.updateById(addressBook);
    }

    @Override
    public AddressBookResDTO getDefaultAddress() {
        Long userId = UserContext.currentUserId();
        AddressBook addressBook = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getIsDefault, 1)
                .one();
        return BeanUtils.copyProperties(addressBook, AddressBookResDTO.class);
    }
}
